<template>
  <div class="app-container">
    <div class="filterDiv">
      <el-input v-model="listQuery.userName" size="small" placeholder="用户名" style="width: 200px;" class="filter-item" />
      <el-button size="small" type="primary" round @click="getList">查询</el-button>
      <el-button v-permiss="['901020']" size="small" class="filter-item" type="primary" round style="float:right;" @click="handleAdd">新增</el-button>
    </div>
    <div class="contentDiv">
      <el-table :key="tableKey" v-loading="listLoading" :data="tableData" fit highlight-current-row style="width: 100%;" size="small">
        <el-empty slot="empty" :image-size="120" description="暂无数据" />
        <el-table-column label="序号" type="index" width="50" align="center" />
        <el-table-column label="企业代码">
          <template slot-scope="{row}">
            <span>{{ row.orgCode }}</span>
          </template>
        </el-table-column>
        <el-table-column label="用户账号">
          <template slot-scope="{row}">
            <span>{{ row.userAccount }}</span>
          </template>
        </el-table-column>
        <el-table-column label="用户名">
          <template slot-scope="{row}">
            <span>{{ row.userName }}</span>
          </template>
        </el-table-column>
        <el-table-column label="员工">
          <template slot-scope="{row}">
            <span>{{ row.staffName }}</span>
          </template>
        </el-table-column>
        <el-table-column label="管理员" align="center">
          <template slot-scope="{row}">
            <span>{{ row.isAdmin==1 ? '是' : '否' }}</span>
          </template>
        </el-table-column>
        <el-table-column label="单据查询权限" align="center">
          <template slot-scope="{row}">
            <span>{{ row.queryType==1 ? '自己' : '全部' }}</span>
          </template>
        </el-table-column>
        <el-table-column label="状态" align="center">
          <template slot-scope="{row}">
            <span>{{ row.status==0?"正常":(row.status==5 ? '受限' : '其它') }}</span>
          </template>
        </el-table-column>
        <el-table-column label="APP/小程序" align="center">
          <template slot-scope="{row}">
            <el-radio-group v-model="row.loginAppType" @change="appChange($event, row.id)">
              <el-radio :label="0">禁止</el-radio>
              <el-radio :label="1">销售</el-radio>
              <el-radio :label="2">库管</el-radio>
              <el-radio :label="3">老板</el-radio>
            </el-radio-group>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" width="220">
          <template slot-scope="{row}">
            <el-button v-permiss="['901030']" type="text" size="small" @click="handleAssign(row)">分配角色</el-button>
            <el-button v-permiss="['901030']" type="text" size="small" @click="handleCompile(row)">编辑</el-button>
            <el-button v-permiss="['901060']" type="text" size="small" @click="handleDel(row.id)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <el-dialog :close-on-click-modal="false" :title="dialogStatus=='create'?'新增用户':'修改用户'" :visible.sync="dialogVisible" width="650px">
      <el-form ref="dataForm" :rules="rules" :model="form" :inline="true" label-position="right" label-width="100px" style="width: 610px; margin-left:10px;">
        <el-form-item label="用户账号" prop="userAccount">
          <el-input v-model="form.userAccount" placeholder="用户账号" />
        </el-form-item>
        <el-form-item label="用户名" prop="userName">
          <el-input v-model="form.userName" placeholder="用户名" />
        </el-form-item>
        <el-form-item label="审核人签名" prop="sign2">
          <el-input v-model="form.sign2" placeholder="审核人签名" />
        </el-form-item>
        <el-form-item label="手机号" prop="mobile">
          <el-input v-model="form.mobile" placeholder="手机号" />
        </el-form-item>
        <el-form-item label="邮箱" prop="mail">
          <el-input v-model="form.mail" placeholder="邮箱" />
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-select v-model="form.status" style="width:185px">
            <el-option :value="0" label="正常" />
            <el-option :value="5" label="受限" />
            <el-option :value="9" label="禁用" />
          </el-select>
        </el-form-item>
        <el-form-item v-if="dialogStatus=='create'" label="密码" prop="password">
          <el-input v-model="form.password" type="password" placeholder="密码" />
        </el-form-item>
        <el-form-item v-if="dialogStatus=='create'" label="确认密码" prop="againPassword">
          <el-input v-model="form.againPassword" type="password" placeholder="确认密码" />
        </el-form-item>
        <el-form-item label="员工" prop="staffId">
          <el-select v-model="form.staffId" style="width:185px">
            <el-option v-for="item in staffList" :key="item.id" :value="item.id" :label="item.staffName" />
          </el-select>
        </el-form-item>
        <el-form-item label="单据查询权限" prop="queryType">
          <el-radio v-model="form.queryType" :label="0">自己</el-radio>
          <el-radio v-model="form.queryType" :label="1">全部</el-radio>
        </el-form-item>
        <el-form-item label="APP/小程序" prop="loginAppType" style="margin-right:95px">
          <el-radio v-model="form.loginAppType" :label="0">禁止</el-radio>
          <el-radio v-model="form.loginAppType" :label="1">销售</el-radio>
          <el-radio v-model="form.loginAppType" :label="2">库管</el-radio>
          <el-radio v-model="form.loginAppType" :label="3">老板</el-radio>
        </el-form-item>
        <el-form-item label="是否管理员" prop="isAdmin">
          <el-radio v-model="form.isAdmin" :label="1">是</el-radio>
          <el-radio v-model="form.isAdmin" :label="0">否</el-radio>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer" align="center">
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="save()">确定</el-button>
      </div>
    </el-dialog>
    <el-dialog :close-on-click-modal="false" title="分配角色" :visible.sync="dialogVisible1" :show-close="false" ::close-on-click-modal="false" width="500px">
      <el-form ref="dataForm" style="width: 460px">
        <el-table ref="checkTable" :data="dataList" border fit highlight-current-row style="width: 100%;" size="small" row-key="id" @selection-change="selectChange" @select-all="selectAll">
          <el-table-column type="selection" width="50" align="center" :reserve-selection="true" />
          <el-table-column label="序号" type="index" width="50" align="center" />
          <el-table-column label="角色代码">
            <template slot-scope="{row}">
              <span>{{ row['roleCode'] }}</span>
            </template>
          </el-table-column>
          <el-table-column label="角色名称">
            <template slot-scope="{row}">
              <span>{{ row['roleName'] }}</span>
            </template>
          </el-table-column>
        </el-table>
      </el-form>
      <div slot="footer" class="dialog-footer" align="center">
        <el-button @click="cancelHanle()">取消</el-button>
        <el-button type="primary" @click="updateAssign()">确定</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
import { getUserList, saveUser, delUser, getRole } from '@/api/user'
import { getStaff, getRoleListByUserIdAppsId, updateUserIdByRoleIdList } from '@/api/basedata'
import { getStrByData } from '@/utils'
export default {
  name: 'UserList',
  data() {
    return {
      tableKey: 0,
      tableData: [],
      staffList: [],
      dialogTit: '',
      dialogType: '',
      dataList: [],
      assignType: 0,
      handleObj: {},
      selectIdArr: [],
      total: 0,
      listLoading: true,
      listQuery: {
        UserName: '',
        UserCode: ''
      },
      form: {
        againPassword: '',
        auditLevel1: '',
        auditLevel2: '',
        id: '',
        mail: '',
        mobile: '',
        orgType: '',
        password: '',
        roleId: '888888',
        queryType: 0,
        staffId: '',
        sign2: '',
        status: 0,
        userAccount: '',
        userName: '',
        loginAppType: 0,
        isAdmin: 0
      },
      resetform: {
        againPassword: '',
        auditLevel1: '',
        auditLevel2: '',
        id: '',
        mail: '',
        mobile: '',
        orgType: '',
        password: '',
        roleId: '888888',
        queryType: 0,
        staffId: '',
        sign2: '',
        status: 0,
        userAccount: '',
        loginAppType: 0,
        userName: '',

        isAdmin: 0
      },
      dialogVisible: false,
      dialogVisible1: false,
      dialogStatus: '',
      rules: {
        userName: [
          { required: true, message: '用户名不能为空', trigger: 'change' }
        ],
        password: [
          { required: true, message: '密码不能为空', trigger: 'change' }
        ],
        mobile: [
          { required: true, message: '手机号不能为空', trigger: 'change' }
        ],
        mail: [{ required: true, message: '邮箱不能为空', trigger: 'change' }],
        userAccount: [
          { required: true, message: '用户账号不能为空', trigger: 'change' }
        ],
        againPassword: [
          { required: true, message: '确认密码不能为空', trigger: 'change' }
        ]
      }
    }
  },
  created() {
    this.getList()
    getStaff().then((res) => {
      this.staffList = res.data.data
    })
  },
  methods: {
    getList() {
      this.listLoading = true
      getUserList(this.listQuery).then((res) => {
        this.listLoading = false
        this.tableData = res.data.data
      })
    },
    selectAll(selection) {
      var arr = []
      for (var i = 0; i < selection.length; i++) {
        arr.push(selection[i].id)
      }
      this.selectIdArr = arr
    },
    selectChange(selection) {
      var arr = []
      for (var i = 0; i < selection.length; i++) {
        arr.push(selection[i].id)
      }
      this.selectIdArr = arr
    },
    handleAssign(row) {
      this.dialogVisible1 = true
      this.handleObj = row
      getRole().then(resp => {
        this.dataList = resp.data.data
        getRoleListByUserIdAppsId({ userId: row.id }).then(res => {
          this.selectIdArr = getStrByData(res.data.data)
          var selectIds = this.selectIdArr.join(',')
          this.dataList.forEach(row => {
            if (selectIds.indexOf(row.id) >= 0) {
              this.$refs.checkTable.toggleRowSelection(row, true)
            }
          })
        })
      })
    },
    updateAssign() {
      var obj = { userId: this.handleObj.id, roleIdList: this.selectIdArr }
      updateUserIdByRoleIdList(obj).then(res => {
        if (res.data.errorCode === '0') {
          this.cancelHanle()
          this.$message.success('分配角色成功')
        }
      })
    },
    cancelHanle() {
      this.dialogVisible1 = false
      this.$refs.checkTable.clearSelection()
    },
    handleAdd(obj) {
      this.dialogVisible = true
      this.dialogStatus = 'create'
      for (var key in this.form) {
        this.form[key] = this.resetform[key]
      }
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    handleCompile(obj) {
      this.dialogVisible = true
      this.dialogStatus = 'update'
      for (var key in this.form) {
        this.form[key] = obj[key]
      }
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    save() {
      this.form.auditLevel1 = '1'
      this.form.auditLevel2 = '1'
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          saveUser(this.form).then((res) => {
            if (res.data.errorCode === '0') {
              this.getList()
              this.dialogVisible = false
              this.$message.success(
                this.dialogStatus === 'create' ? '新增成功' : '修改成功'
              )
            }
          })
        }
      })
    },
    handleDel(id) {
      this.$confirm('确定删除该用户？', '提示', {
        confirmButtonText: '确定',
        closeOnClickModal: false,
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        delUser({ id: id }).then((res) => {
          if (res.data.errorCode === '0') {
            this.getList()
            this.$message.success('删除用户成功！')
          }
        })
      })
    }
  }
}
</script>
